/****************************************************
	文件：GameRoot.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/5/15 21:13:59
	功能：游戏根节点（入口）
*****************************************************/

using System;
using UnityEngine;
using HTUtility;
using System.Collections.Generic;
using UnityEngine.EventSystems;

namespace AIBehavior
{
    public class GameRoot : MonoSingleton<GameRoot>
    {
        [Tooltip("AIEntity预制体")]
        public GameObject AIEntityPrefab;
        [Tooltip("AI数据")]
        public AIData AIData;
        [Tooltip("Obstacle预制体")]
        public GameObject ObstaclePrefab;
        [Tooltip("Obstacle减速半径")]
        public float ObstacleRadius;
        [Tooltip("Obstacle减速半径的Gizmos颜色")]
        public Color ObstacleGizmosColor = new Color(0f, 1f, 1f, 0.2f);

        private Ray mRay => Camera.main.ScreenPointToRay(Input.mousePosition);
        private List<IEntity> mEntityList;
        private List<GameObject> mEntityGoList;
        /// <summary>
        /// 是否开始监听鼠标点击
        /// </summary>
        private bool mListenMouseDown = false;

        public ReactiveProperty<Vector3> Pos;

        private void Awake()
        {
            Pos = new ReactiveProperty<Vector3>(Vector3.zero);
            SubscribeReactiveProperty();
            Init();
        }
        private void Init()
        {
            mEntityList = new List<IEntity>();
            mEntityGoList = new List<GameObject>();
            UIMgr.Instance.Init();
            Debug.Log("GameRoot init done.");
        }
        private void SubscribeReactiveProperty()
        {
            Pos.Subscribe(v =>
            {
                Debug.LogFormat("鼠标点击坐标：（{0} , {1}）", Math.Round(v.x, 2), Math.Round(v.z, 2));
            });
        }
        private void Update()
        {
            InputHandler();
        }
        private void FixedUpdate()
        {
            if (mEntityList != null && mEntityList.Count > 0)
            {
                foreach (IEntity entity in mEntityList)
                {
                    entity.Do();
                }
            }
        }
        private void InputHandler()
        {
            if (Input.GetMouseButton(0) && mListenMouseDown)
            {
                RaycastHit raycastHit;
                if (Physics.Raycast(mRay, out raycastHit, float.MaxValue, 1 << 9))  //只与 第9层lay 做射线检测
                {
                    if (UIMgr.Instance.CheckUIRaycast())
                    {
                        mListenMouseDown = false;
                        return;  //屏蔽UI层
                    }
                    Pos.Value = raycastHit.point;
                }
            }
            if (Input.GetKeyDown(KeyCode.O))  //创建 Obstacle
            {
                AIData.ObstacleList.Add(EntityFactory.CreateObstacle(ObstaclePrefab, Pos.Value));
            }
        }

        /// <summary>
        /// 重置当前鼠标点击位置
        /// </summary>
        public void ResetClickPos()
        {
            Pos.Value = Vector3.zero;
        }
        /// <summary>
        /// 选择 AI Behavior
        /// </summary>
        public void SelectBehavior(BehaviorType behaviorType)
        {
            GameObject entityGo;
            mEntityList.Add(EntityFactory.Create(behaviorType, ref AIData, AIEntityPrefab, Vector3.zero, out entityGo));
            mEntityGoList.Add(entityGo);
            mListenMouseDown = true;
        }
        /// <summary>
        /// 重置 AI Behavior
        /// </summary>
        public void ResetBehavior()
        {
            foreach (GameObject entityGo in mEntityGoList)
            {
                DestroyImmediate(entityGo);
            }
            mEntityList.Clear();
            mEntityGoList.Clear();
            mListenMouseDown = false;

            if (AIData.ObstacleList == null)
            {
                AIData.ObstacleList = new List<Obstacle>();
            }
            else if (AIData.ObstacleList.Count > 0)
            {
                foreach (Obstacle obstacle in AIData.ObstacleList)
                {
                    DestroyImmediate(obstacle.gameObject);
                }
                AIData.ObstacleList.Clear();
            }
        }
    }
}